<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { useLoading } from '@sa/hooks';
import {
  fetchCreateWechatPayConfig,
  fetchUpdateWechatPayConfig,
  uploadFile
} from '@/service/api/business/system-config';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';

defineOptions({
  name: 'WechatPayConfigOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Business.WechatPayConfig | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule, patternRules } = useFormRules();
const { loading: submitLoading, startLoading: startSubmitLoading, endLoading: endSubmitLoading } = useLoading();
const { loading: uploadLoading, startLoading: startUploadLoading, endLoading: endUploadLoading } = useLoading();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增微信支付配置',
    edit: '编辑微信支付配置'
  };
  return titles[props.operateType];
});

type Model = Api.Business.WechatPayConfigOperateParams;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    productId: '',
    templateName: '',
    remark: '',
    appId: '',
    mchId: '',
    apiKey: '',
    signVerify: '',
    payPublicKeyId: '',
    payPublicKey: '',
    mchApiCert: '',
    mchApiKey: '',
    status: 0,
    merchantId: '',
    privateKeyPath: '',
    publicKeyPath: '',
    publicKeyId: '',
    merchantSerialNumber: '',
    apiV3Key: ''
  };
}

type RuleKey = Extract<
  keyof Model,
  'productId' | 'templateName' | 'appId' | 'mchId' | 'apiKey' | 'signVerify' | 'status'
>;

const rules: Record<RuleKey, App.Global.FormRule | App.Global.FormRule[]> = {
  productId: createRequiredRule('产品编号不能为空'),
  templateName: createRequiredRule('模板名称不能为空'),
  appId: createRequiredRule('应用ID不能为空'),
  mchId: createRequiredRule('商户ID不能为空'),
  apiKey: createRequiredRule('支付秘钥不能为空'),
  signVerify: createRequiredRule('验签方式不能为空'),
  status: createRequiredRule('启用状态不能为空')
};

// 文件上传处理
async function handleFileUpload(event: Event, field: keyof Model) {
  const input = event.target as HTMLInputElement;
  if (!input.files || input.files.length === 0) return;

  const file = input.files[0];
  startUploadLoading();

  try {
    const { error, data } = await uploadFile(file);
    if (!error && data) {
      model[field] = data.fileUrl;
      window.$message?.success('文件上传成功');
    } else {
      window.$message?.error('文件上传失败');
    }
  } catch (error) {
    console.error('文件上传错误:', error);
    window.$message?.error('文件上传失败');
  } finally {
    endUploadLoading();
    input.value = ''; // 清空文件选择
  }
}

// 触发文件选择
function triggerFileInput(field: keyof Model) {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.pem,.key,.crt,.txt,.cer'; // 限制上传证书文件类型
  input.onchange = (event) => handleFileUpload(event, field);
  input.click();
}

// 查看文件
function viewFile(fileUrl: string) {
  if (fileUrl) {
    window.open(fileUrl, '_blank');
  }
}

// 删除文件
function removeFile(field: keyof Model) {
  model[field] = '';
}

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  startSubmitLoading();

  try {
    if (props.operateType === 'add') {
      const { error } = await fetchCreateWechatPayConfig(model);
      if (error) return;
    }

    if (props.operateType === 'edit') {
      const { error } = await fetchUpdateWechatPayConfig(model);
      if (error) return;
    }

    window.$message?.success($t('common.updateSuccess'));
    closeDrawer();
    emit('submitted');
  } catch (error) {
    console.error('操作失败:', error);
  } finally {
    endSubmitLoading();
  }
}

const options = [
  {
    label: '微信支付公钥',
    value: '微信支付公钥'
  }
];

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="800" class="max-w-90%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NDivider>基本信息</NDivider>
        <NFormItem label="产品编号" path="productId">
          <NInput v-model:value="model.productId" placeholder="请输入产品编号" />
        </NFormItem>
        <NFormItem label="模板名称" path="templateName">
          <NInput v-model:value="model.templateName" placeholder="请输入模板名称" />
        </NFormItem>
        <NFormItem label="备注" path="remark">
          <NInput v-model:value="model.remark" type="textarea" placeholder="请输入备注信息" />
        </NFormItem>

        <NDivider>微信支付配置</NDivider>
        <NFormItem label="应用ID" path="appId">
          <NInput v-model:value="model.appId" placeholder="请输入微信应用ID" />
        </NFormItem>
        <NFormItem label="商户ID" path="merchantId">
          <NInput v-model:value="model.merchantId" placeholder="请输入微信商户ID" />
        </NFormItem>
        <NFormItem label="支付秘钥" path="apiV3Key">
          <NInput
            v-model:value="model.apiV3Key"
            type="password"
            show-password-on="click"
            placeholder="请输入微信支付V3秘钥"
          />
        </NFormItem>
        <NFormItem label="验签方式" path="signVerify">
          <NSelect v-model:value="model.signVerify" placeholder="请输入验签方式" :options="options">
          </NSelect>
        </NFormItem>
        <NFormItem label="微信支付公钥ID" path="publicKeyId">
          <NInput v-model:value="model.publicKeyId" placeholder="请输入微信支付公钥ID" />
        </NFormItem>

        <NFormItem label="商户证书序列号" path="merchantSerialNumber">
          <NInput v-model:value="model.merchantSerialNumber" placeholder="请输入商户证书序列号" />
        </NFormItem>

<!--        &lt;!&ndash; 微信支付公钥文件上传 &ndash;&gt;-->
<!--        <NFormItem label="微信支付公钥文件">-->
<!--          <div class="flex items-center gap-2">-->
<!--            <NButton :loading="uploadLoading" @click="triggerFileInput('payPublicKey')">-->
<!--              选择文件-->
<!--            </NButton>-->
<!--            <span v-if="model.payPublicKey" class="text-green-600">已上传</span>-->
<!--            <NButton v-if="model.payPublicKey" text @click="viewFile(model.payPublicKey)" type="primary">-->
<!--              查看-->
<!--            </NButton>-->
<!--            <NButton v-if="model.payPublicKey" text @click="removeFile('payPublicKey')" type="error">-->
<!--              删除-->
<!--            </NButton>-->
<!--          </div>-->
<!--        </NFormItem>-->

        <!-- 商户API证书CERT文件上传 -->
        <NFormItem label="商户API证书私钥">
          <div class="flex items-center gap-2">
            <NButton @click="triggerFileInput('privateKeyPath')" :loading="uploadLoading">
              选择文件
            </NButton>
            <span v-if="model.privateKeyPath" class="text-green-600">已上传</span>
            <NButton v-if="model.privateKeyPath" text @click="viewFile(model.privateKeyPath)" type="primary">
              查看
            </NButton>
            <NButton v-if="model.privateKeyPath" text @click="removeFile('privateKeyPath')" type="error">
              删除
            </NButton>
          </div>
        </NFormItem>

        <!-- 商户API证书KEY文件上传 -->
        <NFormItem label="商户API证书公钥">
          <div class="flex items-center gap-2">
            <NButton @click="triggerFileInput('publicKeyPath')" :loading="uploadLoading">
              选择文件
            </NButton>
            <span v-if="model.publicKeyPath" class="text-green-600">已上传</span>
            <NButton v-if="model.publicKeyPath" text @click="viewFile(model.publicKeyPath)" type="primary">
              查看
            </NButton>
            <NButton v-if="model.publicKeyPath" text @click="removeFile('publicKeyPath')" type="error">
              删除
            </NButton>
          </div>
        </NFormItem>

        <NDivider>状态设置</NDivider>
        <NFormItem label="启用状态" path="status">
          <DictRadio v-model:value="model.status" dict-code="sys_normal_disable" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped>
.flex-center {
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>
